package com.cloud.bssp.thread.sync.AQStest;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @description： 自定义锁
 * @author：weirx
 * @date：2022/1/13 14:05
 * @version：3.0
 */
public class MyLock implements Lock {

    MyLockSynchronizer myLockSynchronizer = new MyLockSynchronizer();

    @Override
    public void lock() {
        // 尝试获取锁，失败则加入等待队列
        myLockSynchronizer.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        // 尝试获取锁，失败则加入等待队列, 可中断
        myLockSynchronizer.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        // 尝试获取锁，不加入等待队列
        return myLockSynchronizer.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        // 尝试获取锁，不加入等待队列,有实现
        return myLockSynchronizer.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        // 释放锁
        myLockSynchronizer.release(1);
    }

    @Override
    public Condition newCondition() {
        // 条件变量
        return myLockSynchronizer.newCondition();
    }
}
